package com.lzw.breezeNovel.webApp.message;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleStateHandler;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.webApp.message
 * @date 2025/3/27
 * @description 配置netty
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class NettyWebSocketServer {

    /**
     * 接收客户端的连接请求
     */
    private  EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    /**
     * 处理客户端的读写连接
     */
    private  EventLoopGroup workerGroup = new NioEventLoopGroup();

    /**
     * 注入HandelWebSocket
     */
    @Resource
    private HandelWebSocket handelWebSocket;

    /**
     * 销毁服务器
     */
    @PreDestroy
    public void destroy(){
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

    /**
     * 启动服务器
     */
    @Async
    public void start(){
        try {
            //创建ServiceBootstrap
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //配置服务器的线程组
            serverBootstrap.group(bossGroup, workerGroup)
                    //指定NIO类型的通道
                    .channel(NioServerSocketChannel.class)
                    //设置通道的初始化器
                    .childHandler(new ChannelInitializer<>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            //添加自定义的处理器
                            pipeline.addLast(new HttpServerCodec());
                            //聚合HTTP消息
                            pipeline.addLast(new HttpObjectAggregator(1024 * 64));
                            //设置心跳
                            pipeline.addLast(new IdleStateHandler(6000, 0, 0, TimeUnit.SECONDS));
                            //自定义心跳处理器
                            pipeline.addLast( new HeartBeatHandler());
                            //将http协议转换成websocket协议
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws",null,true,1024 * 64,true,true,10001));
                            //自定义websocket处理器
                            pipeline.addLast(handelWebSocket);
                        }
                    });
            //绑定端口并启动服务器
            ChannelFuture future = serverBootstrap.bind(8002).sync();
            log.info("服务器启动成功");
            //等待服务器端口关闭
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
